package cn.zj.configuration;

import cn.zj.testScript.TestSuiteByExcel;
import cn.zj.util.*;
import org.apache.log4j.xml.DOMConfigurator;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;

import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.zj.util.WaitUtil.waitWebElement;

//本类实现测试代码与excel测试文件中的关键字的映射关系
public class KeyWordsAction {
    public static WebDriver driver;

    public  static  ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    public  static InputStream is = classloader.getResourceAsStream("objectMap.properties");
    public static ObjectMap objectMap =new ObjectMap(is);

    static {
        DOMConfigurator.configure("log4j");}
    //声明存储定位表达配置文件的ObjectMap对象



    //此方法的名称对应Excel文件“关键字”列中的open_browser，开启指定浏览器
    public static void open_browser(String string,String browserName) {

//        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
//        InputStream is = classloader.getResourceAsStream("objectMap.properties");
//        objectMap = new ObjectMap(is);
        if (browserName.equals("ie")) {

        } else if (browserName.equals("chrome")) {
            String path = classloader.getResource("chromedriver.exe").getPath();
            System.setProperty("webdriver.chrome.driver", path);
            driver = new ChromeDriver();
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
            Log.info("Chrome浏览器实例已经声明");
        } else {

        }
    }

    //设置浏览器访问网址
    public static void navigate(String string,String url) {

        driver.get(url);
        Log.info("浏览器访问网址"+url);
    }

    //登录用户名输入内容
    public static void input(String locatorExpression,String inputString) {

        try {
            driver.findElement(objectMap.getLocator(locatorExpression)).clear();
            Log.info("清除------"+locatorExpression+"-----输入框内容");
            driver.findElement(objectMap.getLocator(locatorExpression)).sendKeys(inputString);
            Log.info("在"+locatorExpression+"输入框中输入"+inputString);
        } catch (Exception e) {
            TestSuiteByExcel.testResult = false;
            Log.info("在"+locatorExpression+"输入框中输入"+inputString+"时出现异常，具体异常信息："+e.getMessage());
            e.printStackTrace();
        }
    }

    //登录密码输入内容
//    public static void input_passWord(String password) throws Exception{
//        System.out.println("收到的参数值：" + password);
//        driver.findElement(objectMap.getLocator("login.passWord")).clear();
//        driver.findElement(objectMap.getLocator("login.passWord")).sendKeys(password);
//    }

    //登录按钮点击操作
    public static void click(String locatorExpression,String string) throws Exception{
        try {
            driver.findElement(objectMap.getLocator(locatorExpression)).click();
            Log.info("单击"+locatorExpression+"页面元素成功");
            WaitUtil.sleep(2000);
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            Log.info("单击"+locatorExpression+"页面元素失败，具体异常信息："+e.getMessage());
            e.printStackTrace();
        }


    }

    //隐式等待
    public static void waitFor_Element(String locatorExpression,String string) throws Exception{
        try {
            driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
            waitWebElement(driver, objectMap.getLocator(locatorExpression));
            Log.info("显式等待"+locatorExpression+"元素出现成功");
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            Log.info("显式等待"+locatorExpression+"元素出现失败，具体异常信息："+e.getMessage());
            e.printStackTrace();
        }

    }

    //等待页面元素可被点击
    public static void waitForElementEnabled(String locatorExpression,String string){
        WebDriverWait wait = new WebDriverWait(driver,15);
        try {
            wait.until(ExpectedConditions.elementToBeClickable(objectMap.getLocator(locatorExpression)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //自定义等待
    public static WebElement isElementPresent(String locatorExpression, String time){
        WebElement ele = null;

        for(int i=0;i<Integer.valueOf(time);i++){
            try{

                ele = driver.findElement(objectMap.getLocator(locatorExpression));
                break;
            } catch(Exception e){
                try{
                    Thread.sleep(2000);
                } catch(InterruptedException e1){
                    System.out.println("Waiting for element to appear on DOM");
                }
            }
        }
        return ele;

    }


    //按Tab键的操作
    public static void press_Tab(String locatorExpression,String string){
        try {
            Thread.sleep(2000);
            KeyBoardUtil.pressTabKey();
            Log.info("按Tab键成功");
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            Log.info("按Tab键时出现异常，具体异常信息："+e.getMessage());
            e.printStackTrace();
        }
    }
    //休眠方法
    public static void sleep(String string,String sleepTime){
        try {
            WaitUtil.sleep(Integer.parseInt(sleepTime)*1000);
            Log.info("休眠"+Integer.parseInt(sleepTime)/1000+"秒成功");
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            Log.info("线程休眠时出现异常，具体异常信息："+e.getMessage());
            e.printStackTrace();
        }
    }

    //断言判断
    public static void assert_String(String string,String assertString) throws IOException, InterruptedException {
        try {
            Assert.assertTrue(driver.getPageSource().contains(assertString));
            Log.info("成功断言关键字"+assertString);
        }catch (Exception e){
            TestSuiteByExcel.testResult = false;
            ImagesUtil.SreenShot(driver);
            Log.info("出现断言失败，具体异常信息："+e.getMessage());

        }

    }

    //关闭浏览器
    public static void close_browser(String string1,String string2) {
        try {
            driver.quit();
            Log.info("成功关闭浏览器");
        } catch (Exception e) {
            TestSuiteByExcel.testResult =  false;
            e.printStackTrace();
            Log.info("关闭浏览器失败，具体异常信息："+e.getMessage());
        }
    }

    //操作单选下拉框
    public static void operateDropList(String locatorExpression,String string){
        try {
            //找到指定下拉框
             Select dropList = new Select(driver.findElement(objectMap.getLocator(locatorExpression)));
             dropList.selectByIndex(Integer.valueOf(string));
            Log.info("下拉框"+locatorExpression+"已选择第"+string);
        } catch (Exception e) {
            e.printStackTrace();
            Log.info("下拉框"+locatorExpression+"选择失败");
        }

    }

    //操作单选框
    public static void operateRadio(String locatorExpression,String string){
        try {
            WebElement radio = driver.findElement(objectMap.getLocator(locatorExpression));
            if(!radio.isSelected())
                radio.click();
            Assert.assertTrue(radio.isSelected());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //操作复选框组
    public static void operateCheckBox(String locatorExpression,String string){
        try {
            List<WebElement> radios = driver.findElements(objectMap.getLocator(locatorExpression));
            for(WebElement r : radios){
                if(r.getAttribute("value").equals(string)){
                    if(!r.isSelected()){
                        r.click();
                        Assert.assertTrue(r.isSelected());
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //操作日历控件

    public  static void operateDataTool(String locatorExpression,String dataString) throws Exception {

        WebElement data = driver.findElement(objectMap.getLocator(locatorExpression));
        ToolUtil.setAttribute(driver,data,"spellcheck","true");
        data.sendKeys(dataString);
    }

    //图片上传

    public  static void uploadPhoto(String locatorExpression,String photoPath) throws InterruptedException, AWTException {
        // 指定图片的路径
        StringSelection sel = new StringSelection(photoPath);

        // 把图片文件路径复制到剪贴板
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, null);


        // 新建一个Robot类的对象
        Robot robot = new Robot();
        Thread.sleep(1000);

        // 按下回车
        robot.keyPress(KeyEvent.VK_ENTER);

        // 释放回车
        robot.keyRelease(KeyEvent.VK_ENTER);

        // 按下 CTRL+V
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);

        // 释放 CTRL+V
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_V);
        Thread.sleep(1000);

        // 点击回车 Enter
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
    }
}
